<template>
	<view class="page">
		<view class="top_img">
			<image style="width: 500rpx;height: 80rpx;" src="https://beihai-food.oss-cn-beijing.aliyuncs.com/04.png">
			</image>
			<view class="f14" style="color: #fff;margin-top: 16rpx;">
				每周二12:00至周五12:00开放
			</view>

		</view>
		<view class="content">
			<calendar :mainData="foodDateType" @cutWeek="cutWeek"></calendar>
			<view class="flex_between">
				<view class="flex_align_conter">
					<button class="login-btn cu-btn block bg-green-plain round" @click="">按日复制</button>
					<button class="login-btn cu-btn block bg-green-plain round" @click=""
						style="margin-left: 20rpx;">按周复制</button>
				</view>
				<button class="login-btn cu-btn block bg-green-plain  round" @click="">智能推荐</button>
			</view>
			<view class="tabs">
				<u-tabs :activeStyle="{ 'color': '#0EB275' }" :itemStyle="{'height': '80rpx' }" lineColor="#0EB275"
					lineWidth="28" :list="tabsList" @click="tabsClick" :current="tabsCurrent"></u-tabs>
			</view>
			<view class="flex meal_main" style="">
				<view class="tabsSide h100">
					<view class="t" v-for="(item,index) in tabsSide" @click="tabsSideCilck(index)">
						<view :class="{'t_active':index == tabsSideIndex}">
							{{item}}
						</view>
					</view>
				</view>
				<view class="flex1">
					<view class="right_side">
						<setMealReservation v-for="item in packageList" :item="item" @updateNum="handleUpdateNum">
						</setMealReservation>
					</view>
				</view>

			</view>
			<view class="" @click="hhhh">

				<shoppingBag :cartList="selectedPackages" @undateData="undateShoppingData"></shoppingBag>
			</view>
		</view>
		<navigationBar tabbarIndex="1"></navigationBar>
	</view>
</template>
<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import navigationBar from '@/components/common/navigationBar.vue'
	import calendar from '@/components/common/calendar.vue'
	import setMealReservation from '@/components/common/setMealReservation.vue'
	import shoppingBag from '@/components/common/shoppingBag.vue'
	import {
		getfoodSetMealAPI,
		getfoodDateTypeAPI
	} from '@/api/index.js'
	// uni.hideTabBar()
	export default {
		name: '',
		components: {
			navigationBar,
			calendar,
			setMealReservation,
			shoppingBag
		},


		data() {
			return {
				paramsData: {
					time: '',
					meals: '',
					state: ''
				},
				foodDateType: [],
				shoppingData: [], // 总数据
				weekIndex: 0,
				tabsSide: ['套餐', '菜品'],
				tabsSideIndex: 0, // 侧面tabs
				tabsCurrent: 0, // 上面tabs
				// selectedPackages: [], // 存放 num > 0 的套餐
				packageData: [], // 一天的数据
				mealsArray: [], //  meals
				packageList: [], // 具体的List
				tabsList: [],

			}

		},
		watch: {
			weekIndex: {
				handler(e) {
					this.packageData = this.shoppingData[e].dictDataList
					this.tabsClick({
						index: 0
					})
				},
				// deep: true,
				// immediate: true
			},
			// tabsCurrent: {
			// 	handler(e) {
			// 		// console.log('tabsCurrent')
			// 		// console.log('this.mealsArray');
			// 		// console.log(this.mealsArray);
			// 	},
			// 	deep: true,
			// 	immediate: true
			// },
		},
		computed: {
			...mapState({
				shoppingBagData: state => state.user.shoppingBagData
			}),
			selectedPackages() {
				return this.shoppingData.map(day => {
					const filteredDay = JSON.parse(JSON.stringify(day)) // 深拷贝避免污染原数据
					const meals = ['meals1', 'meals2']
					const lists = ['comboList', 'dishList']

					meals.forEach(mealKey => {
						lists.forEach(listKey => {
							if (
								filteredDay.dictDataList[mealKey] &&
								filteredDay.dictDataList[mealKey][listKey]
							) {
								filteredDay.dictDataList[mealKey][listKey] =
									filteredDay.dictDataList[mealKey][listKey].filter(
										item => Number(item.saleNum) > 0
									)
							}
						})
					})

					return filteredDay
				})
			}
		},
		onLoad() {
			// this.getfoodSetMeal()
		},
		onShow() {
			this.getShoppingData()
		},
		created() {

		},
		methods: {
			getPackageList() {
				this.packageList = [{
					foodId: 48,
					foodCode: "CP250711366",
					foodName: "尖椒肉丝",
					image: "[{\"status\":\"success\",\"name\":\"菜花.png\",\"size\":746826,\"percentage\":0,\"uid\":1752203706905,\"raw\":{\"uid\":1752203706905},\"url\":\"https://beihai-food.oss-cn-beijing.aliyuncs.com/food/2025/07/11/2025-07-11MC11:15:130a7f9b80da804e2da1517aaa2a429077.png\"}]",
					price: 12.00,
				}]
			},
			addIdsToItems(contentData) {
				return contentData.map(day => {
					const newDay = JSON.parse(JSON.stringify(day)); // 深拷贝
					const meals = ['meals1', 'meals2'];
					const lists = ['comboList', 'dishList'];
					meals.forEach(mealKey => {
						lists.forEach(listKey => {
							const list = newDay.dictDataList?.[mealKey]?.[listKey];
							if (Array.isArray(list)) {
								list.forEach(item => {
									if (!item.lzy_id) { // 如果还没有 id，就生成一个
										item.lzy_id = this
											.generateUniqueId(); // 自定义生成唯一ID的方法
									}
								});
							}
						});
					});

					return newDay;
				});
			},

			// 生成唯一ID的方法（示例）
			generateUniqueId() {
				return 'id_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
			},

			// 使用示例

			async getfoodDateType() {
				const res = await getfoodDateTypeAPI()
				this.foodDateType = res.data
			},
			setTabsList(data) {
				const mealsMap = {
					meals1: {
						id: 1,
						name: '早餐'
					},
					meals2: {
						id: 2,
						name: '午餐'
					},
					meals3: {
						id: 3,
						name: '晚餐'
					},
				};

				const obj = data[0].dictDataList;
				this.tabsList = Object.keys(mealsMap)
					.filter(key => obj.hasOwnProperty(key))
					.map(key => mealsMap[key]);
			},
			async getfoodSetMeal() {
				const res = await getfoodSetMealAPI()
				// console.log(res);
				this.setTabsList(res.data)
				this.shoppingData = this.addIdsToItems(res.data);
				this.packageData = this.shoppingData[this.weekIndex].dictDataList
				this.tabsClick({
					index: 0
				})
				this.persistenceShoppingBag()

			},
			undateShoppingData() {
				this.shoppingData = this.shoppingBagData // vuex获取
				this.packageData = this.shoppingData[this.weekIndex].dictDataList
				this.tabsClick({
					index: this.tabsCurrent
				})
			},
			getShoppingData() {
				if (this.shoppingData.length == 0) {
					// if (true) {
					this.getfoodSetMeal()
					this.getfoodDateType()
					// setTimeout(() => {
					// 	this.shoppingData = JSON.parse(JSON.stringify(this.contentData))
					// 	this.packageData = this.shoppingData[this.weekIndex].dictDataList
					// 	this.tabsClick({
					// 		index: 0
					// 	})
					// }, 500)
				} else {
					this.shoppingData = this.shoppingBagData // vuex获取
					this.packageData = this.shoppingData[this.weekIndex].dictDataList
					this.tabsClick({
						index: 0
					})
				}
			},
			tabsClick(e) {
				// if (this.tabsCurrent == 0) {
				// 	// 早餐
				// 	this.mealsArray = this.packageData.meals1
				// } else if (this.tabsCurrent == 1) {
				// 	// 午饭
				// 	this.mealsArray = this.packageData.meals2
				// }
				// this.tabsSideCilck(this.tabsSideIndex) // 保持之前的状态
				this.tabsCurrent = e.index
				const obj = this.tabsList[e.index]
				if (obj.id == 1) {
					// 早餐
					this.mealsArray = this.packageData.meals1
				} else if (obj.id == 2) {
					// 午饭
					this.mealsArray = this.packageData.meals2
				} else if (obj.id == 3) {
					// 午饭
					this.mealsArray = this.packageData.meals3
				}
				this.tabsSideCilck(this.tabsSideIndex) // 保持之前的状态
			},
			tabsSideCilck(index) {
				this.tabsSideIndex = index
				if (index == 0) {
					// 套餐
					// console.log(this.mealsArray);
					this.packageList = this.mealsArray?.comboList || []

				} else {
					// 菜品
					this.packageList = this.mealsArray?.dishList || []
				}
			},
			initPackageList() {
				this.packageList = this.packageData.meals2.comboList
			},
			cutWeek(e) {
				this.weekIndex = e
			},

			handleUpdateNum(item, e) {
				let target
				if (item.comboId) {
					target = this.packageList.find(i => i.comboId === item.comboId)
					if (target) target.saleNum = e
				} else if (item.foodId) {
					target = this.packageList.find(i => i.foodId === item.foodId)
					if (target) target.saleNum = e
				}
				this.persistenceShoppingBag()
			},
			persistenceShoppingBag() {
				const updatedData = JSON.parse(JSON.stringify(this.shoppingData))
				updatedData[this.weekIndex].dictDataList = this.packageData
				this.$store.commit('SET_SHOPPINGBAGDATA', updatedData)
				// console.log(this.filterContentDataByNum());
			},
			// filterContentDataByNum() {
			// 	// 计算选的套餐和菜品
			// 	return this.shoppingBagData.map(day => {
			// 		const filteredDay = JSON.parse(JSON.stringify(day))
			// 		const meals = ['meals1', 'meals2']
			// 		const lists = ['comboList', 'dishList']
			// 		meals.forEach(mealKey => {
			// 			lists.forEach(listKey => {
			// 				if (filteredDay.dictDataList[mealKey] && filteredDay.dictDataList[
			// 						mealKey][listKey]) {
			// 					filteredDay.dictDataList[mealKey][listKey] =
			// 						filteredDay.dictDataList[mealKey][listKey].filter(item =>
			// 							Number(item.num) > 0)
			// 				}
			// 			})
			// 		})
			// 		return filteredDay
			// 	})
			// },

			hhhh() {
				// console.log(this.shoppingData)
				// console.log(this.selectedPackages)
			},

		}
	}
</script>

<style scoped lang="scss">
	.page {
		position: relative;
		// height: 100vh;
		background: #F2F2F2;
		padding-bottom: 30rpx;

		.top_img {
			display: flex;
			flex-direction: column;
			// justify-content: space-between;
			// padding: 180rpx 40rpx 120rpx;
			padding-top: 120rpx;
			align-items: center;
			width: 100%;
			height: 350rpx;
			background-image: url('https://beihai-food.oss-cn-beijing.aliyuncs.com/03.png');
			// background-size: contain;
			background-size: cover;
			background-repeat: no-repeat;
			font-size: 36rpx;
			font-weight: 500;

			.text {
				font-size: 20rpx;
				color: #fff;
			}
		}

	}

	.content {
		position: relative;
		top: -130rpx;
		padding: 40rpx 20rpx 0;

		.login-btn {
			width: 150rpx;
			height: 44rpx;
			font-size: 28rpx;
			padding: 0;
			border: none;
		}


		.tabs {
			position: relative;
			left: -20rpx;
			// padding-left: 20rpx;
			// margin: 16rpx 0;
			margin-top: 16rpx;
			width: 100vw;
			// height: 80rpx;
			background: #fff;
			z-index: 2;
		}

		.tabsSide {
			position: relative;
			left: -20rpx;
			background-color: #fff;
			width: 120rpx;

			.t {
				text-align: center;
				width: 100%;
				height: 100rpx;
				line-height: 100rpx;
			}

			.t_active {
				position: relative;
				color: #0EB275;
				background-color: #E6F7F1;
			}

			.t_active::after {
				content: "";
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				background: #0EB275;
				z-index: 9;
				width: 60rpx;
				height: 4rpx;
				border-radius: 0px 2px 2px 0px;
				/* 主色 */
				background: #0EB275;
			}
		}

		.meal_main {
			// padding-bottom: 120rpx;
			display: grid;
			grid-template-columns: auto 1fr;
			height: calc(100vh - 760rpx);

			.right_side {
				padding-top: 16rpx;
				padding-bottom: 120rpx;
				height: calc(100vh - 760rpx);
				overflow-y: auto;
			}
		}

		::v-deep .u-tabs__wrapper__nav__item__text {
			font-size: 28rpx;
		}

		::v-deep .u-tabs__wrapper__nav__item {
			width: 160rpx;
		}
	}
</style>